from wtforms import Form, StringField, ValidationError,BooleanField,FileField
from wtforms.validators import Email, EqualTo, Length
from exts import cache
from models.user import UserModel
from .baseform import BaseForm
from flask_wtf.file import FileAllowed


class RegisterForm(BaseForm):
    email = StringField(validators=[Email(message='请输入正确格式的邮箱！')])
    captcha = StringField(validators=[Length(min=4, max=4, message='请输入正确格式的验证码！')])
    username = StringField(validators=[Length(min=2, max=20, message='请输入正确格式的用户名！')])
    password = StringField(validators=[Length(min=6, max=20, message='请输入正确格式的密码！')])
    confirm_password = StringField(validators=[EqualTo('password', message='两次密码不一致！')])

    def validate_email(self, field):
        email = field.data
        # print(email)
        user = UserModel.query.filter_by(email=email).first()
        if user:
            raise ValidationError(message='该邮箱已被注册！')

    def validate_captcha(self, field):
        captcha = field.data
        # print(captcha)
        email = self.email.data
        captcha_cache = cache.get(email)
        # print(captcha_cache)
        # print(type(captcha_cache))
        if not captcha_cache or captcha != captcha_cache:
            raise ValidationError(message='验证码错误！')


class LoginForm(BaseForm):
    email = StringField(validators=[Email(message='请输入正确格式的邮箱！')])
    password = StringField(validators=[Length(min=6, max=20, message='请输入正确格式的密码！')])
    remember = BooleanField()


class EditProfileForm(BaseForm):
    username = StringField(validators=[Length(min=2, max=20, message='请输入正确格式的用户名！')])
    signature = StringField()
    avatar = FileField(validators=[FileAllowed(['jpg', 'jpeg', 'png'], message='文件类型错误！')])

    def validate_signature(self, field):
        signature = field.data
        if len(signature) > 100:
            raise ValidationError(message='签名长度不能超过100个字符！')